<template>
  <div class="time_wrapper">
    <div class="time mr-2">{{ nowtime | timeFilter }}</div>
    <div class="btn">
      <el-button @click="toggleTime">停止time(局部filter)</el-button>
    </div>
    <div>{{ 304000.0 | toThousandFilter }}</div>
  </div>
</template>
<script>
import dayjs from 'dayjs'
export default {
  name: 'timeFilterComponent',
  components: {},
  data() {
    return {
      nowtime: 0,
      isCancel: false, // 是否取消时间
      timeToggle: null // 取消当前运作函数的函数 取消函数
    }
  },
  methods: {
    // setTimeout 模拟 setInterval
    mysetInterval: function (callback, wait) {
      let isCancel = false
      let timer = null
      function fn() {
        if (isCancel) {
          timer && clearTimeout(timer)
          return
        }
        timer = setTimeout(() => {
          callback.call(this)
          fn()
        }, wait)
      }
      callback()
      fn()
      return {
        toggle: () => {
          isCancel = true
        }
      }
    },
    toggleTime() {
      // 第一次按停止就需要取消
      if (!this.isCancel) {
        this?.timeToggle()
      }
      if (this.isCancel) {
        this.startTimeInterval()
      }
      this.isCancel = !this.isCancel
    },
    startTimeInterval() {
      const { toggle } = this.mysetInterval(() => {
        this.nowtime = Date.now()
      }, 1000)
      this.timeToggle = toggle
    }
  },
  mounted() {
    this.startTimeInterval()
    console.log(typeof toggle)
    // setTimeout(() => {
    //   toggle()
    // }, 9000)
  },
  activated: {},
  deactivated: {},
  // 局部过滤
  filters: {
    timeFilter: function (val) {
      if (!val) return dayjs(Date.now).format('YYYY-MM-DD HH:mm:ss')
      return dayjs(+val).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>
<style lang="less" scoped>
.time_wrapper {
  display: inline-flex;
  align-items: center;
  flex-wrap: wrap;
  height: 100%;
  .time {
    font-size: 14px;
  }
}
</style>
